package com.fowo.api.controller.purchase;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.common.model.IdListPo;
import com.fowo.api.common.model.R;
import com.fowo.api.controller.purchase.dto.modifyRemarks;
import com.fowo.api.controller.purchase.vo.wfsShipment;
import com.fowo.api.controller.purchase.vo.wfsinventory;
import com.fowo.api.entity.*;
import com.fowo.api.mapper.ParilistMapper;
import com.fowo.api.model.platformshipping.PlatformshippingVo;
import com.fowo.api.model.wfs.cargo.WfsCargoVo;
import com.fowo.api.model.wfs.cargo.item.WfsCargoItemItemVo;
import com.fowo.api.model.wfs.cargo.item.WfsCargoItemVo;
import com.fowo.api.service.LogisticsReconciliationService;
import com.fowo.api.service.PlatformshippingService;
import com.fowo.api.service.WfsCargoItemService;
import com.fowo.api.service.WfsCargoService;
import com.fowo.api.service.handleWork.synCRate;
import com.fowo.api.service.impl.*;
import com.fowo.api.syncAmazon.service.impl.SyncShipmentServiceImpl;
import com.fowo.api.syncAmazon.service.impl.TmpSyncListingServiceImpl;
import com.fowo.api.walmart.api.WalmartShipmentApi;
import com.fowo.api.walmart.entity.InboundShipmentBo;
import com.fowo.api.walmart.service.SyncWalmartShipmentServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Tag(name = "WFS货件")
@RequestMapping("/api/wfs-cargo-D")
@RestController
public class wfsShipmentController{
    @Resource
    private WfsCargoServiceImpl wfsCargoServiceImpl;
    @Resource
    protected WfsCargoItemServiceImpl wfsCargoItemService;
    @Resource
    private WalmartShipmentApi walmartShipmentApi;
    @Resource
    private PlatformshippingServiceImpl platformshippingService;
    @Resource
    private SyncWalmartShipmentServiceImpl syncWalmartShipmentService;
    @Resource
    private InventoryRealServiceImpl inventoryRealService;
    @Resource
    private LogisticsReconciliationServiceImpl logisticsReconciliationService;
    @Resource
    private ParilistMapper parilistMapper;
    @Resource
    private SyncShipmentServiceImpl syncShipmentServiceImpl;
    @Resource
    private TmpSyncListingServiceImpl tmpSyncListingServiceImpl;
    @Resource
    private synCRate synCate;
    @Operation(summary = "修改备注")
    @PostMapping("modifyRemarks")
    public R create(@Validated @RequestBody modifyRemarks model) {
        UpdateWrapper<LogisticsReconciliation> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id",model.getIds());
        updateWrapper.set("remarks",model.getRemarks());
        logisticsReconciliationService.update(updateWrapper);
        return R.data(updateWrapper);
    }

    @PostMapping("syncListing")
    public R create() {
//        try {
//            tmpSyncListingServiceImpl.syncListing(null);
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
        synCate.getDate();
        return R.data(0);
    }
    //
    @Operation(summary = "根据货件号和店铺同步")
    @PostMapping("shopAndShipmentCode")
    public R shopAndShipmentCode(@RequestBody wfsShipment model) {
        try {
            syncWalmartShipmentService.syncShipmentsByShop(model.getShopId(),model.getListCode());
        } catch (Exception e) {
            return R.fail("同步失败");
        }
        return R.data(0);
    }

    @Operation(summary = "fba根据货件号和店铺同步")
    @PostMapping("shopAndFbaShipmentCode")
    public R shopAndFbaShipmentCode(@RequestBody wfsShipment model) {
        try {
            syncShipmentServiceImpl.manualSyncShipment(model.getShopId(),model.getListCode());
        } catch (Exception e) {
            return R.fail("同步失败");
        }
        return R.data(0);
    }

    @Operation(summary = "重新匹配SKU")
    @PostMapping("againmate")
    public R shopAndShipmentCode(@RequestBody IdListPo po) {
        try {
            List<Long> ids = po.getIds();
            for(int i = 0; i < ids.size(); i++){
                WfsCargoVo voById = wfsCargoServiceImpl.getVoById(ids.get(i));
                Set<String> mskList = voById.getItems().stream().map(x -> x.getMsku()).collect(Collectors.toSet());
                List<Parilist> parilists = parilistMapper.selectList(Wrappers.lambdaQuery(Parilist.class)
                        .eq(Parilist::getShopId, voById.getShopId()).eq(Parilist::getType,"1")
                        .in(Parilist::getMsku,mskList));
                voById.getItems().forEach(x -> {
                    Parilist parilist = parilists.stream().filter(p -> p.getMsku().equals(x.getMsku())).findAny().orElse(null);
                    if(parilist!=null){
                        WfsCargoItemVo wfsCargoItemVo=new WfsCargoItemVo();
                        wfsCargoItemVo.setId(x.getId());
                        wfsCargoItemVo.setProductName(parilist.getProductId());
                        wfsCargoItemVo.setSku(parilist.getSku());
                        try {
                            boolean update = wfsCargoItemService.updateById(wfsCargoItemVo);
                        }catch (Exception e){
                        }
                    }
                });
            }
        } catch (Exception e) {
            return R.fail("同步失败");
        }
        return R.data(0);
    }

    @Operation(summary = "查询可用库存")
    @PostMapping("getInventory")
    public R getiInventory(@RequestBody wfsinventory model) {
     QueryWrapper<InventoryReal> queryWrapper = new QueryWrapper<>();
     List<wfsinventory.inventoryTurnoverVo> inventoryTurnoverList=new ArrayList<>();
        queryWrapper.select("stock_qty");
        queryWrapper.eq("stock_id",model.getWarehouseId());
        for(int i=0;i<model.getItems().size();i++){
            wfsinventory.inventoryTurnoverVo inventoryTurnoverVo = model.getItems().get(i);
            queryWrapper.eq("item_id",inventoryTurnoverVo.getProductId());
            if(inventoryTurnoverVo.getShopId()!=null){
                queryWrapper.eq("shop_id",inventoryTurnoverVo.getShopId());
            }else{
                queryWrapper.isNull("shop_id");
            }
            queryWrapper.isNull("fn_sku");
            InventoryReal one = inventoryRealService.getOne(queryWrapper);
            if(one!=null){
                inventoryTurnoverVo.setQuantity(one.getStockQty());
            }else{
                inventoryTurnoverVo.setQuantity(0L);
            }
            inventoryTurnoverList.add(inventoryTurnoverVo);
        }
        return R.data(inventoryTurnoverList);
    }

    @Operation(summary = "生成发货单")
    @PostMapping("generateshipmentorder")
    public R generateshipmentorder(@RequestBody PlatformshippingVo model) {
        Assert.notNull(model.getSendgoodscode(), "货件编号不能为空");
        long count = model.getItems().stream().filter(x -> x.getProductName() == null).count();
        Assert.isTrue(count==0, "请先配对");
        try {
            Long l = platformshippingService.create(model);
            //更新货件的单号
            //shipmentCode
            WfsCargo one = wfsCargoServiceImpl.getOne(Wrappers.<WfsCargo>query().lambda().eq(WfsCargo::getCargoCode, model.getSendgoodscode()));
            Platformshipping byId = platformshippingService.getById(l);
            one.setShippingListCodes(byId.getShipmentCode());
            wfsCargoServiceImpl.updateById(one);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return R.data(0);
    }

    @Operation(summary = "新增货件")
    @PostMapping("addWfs")
    public R<Long> addWfs(@Validated @RequestBody WfsCargoVo model) {
        return R.data(() -> wfsCargoServiceImpl.create(model));
    }

}
